import time

import requests
from lxml import etree
import threading
from queue import Queue


class QiubaiSpider:

    def __init__(self):
        self.url_temp = 'https://www.qiushibaike.com/8hr/page/{}/'
        self.headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
        self.url_quene = Queue()
        self.html_quene = Queue()
        self.content_quene = Queue()
        self.nums = 1

    def get_url_list(self):
        for i in range(1, 20):
            self.url_quene.put(self.url_temp.format(i))

    def parse_url(self):
        while True:
            url = self.url_quene.get()
            print(url)
            response = requests.get(url, headers=self.headers)
            time.sleep(1)
            self.html_quene.put(response.content.decode())
            self.url_quene.task_done()

    def get_content_list(self):
        while True:
            html_str = self.html_quene.get()
            html = etree.HTML(html_str)
            div_list = html.xpath('//div[@id="content-left"]/div')
            content_list = []
            for div in div_list:
                item = dict()
                item['content'] = div.xpath('.//div[@class="content"]/span/text()')
                item['content'] = [i.replace('\n', '') for i in item['content']]
                # item['author_gender'] = div.xpath('.//div[contains(@class,"articleGender")]/@class')
                # item['author_gender'] = item['author_gender'][0].split(' ')[-1].replace('Icon', '') if len(item['author_gender'])>0 else None
                # item['author_age'] = div.xpath('.//div[contains(@class,"articleGender")]/text()')
                # item['author_age'] = item['author_age'][0] if len(item['author_age']) > 0 else None
                item['content_img'] = div.xpath('.//div[@class="thumb"]/a/img/@src')
                item['content_img'] = 'https:'+item['content_img'][0] if len(item['content_img']) > 0 else None
                # item['author_img'] = div.xpath('.//div[@class="author clearfix"]//img/@src')
                # item['author_img'] = 'https:'+item['author_img'][0] if len(item['author_img']) > 0 else None
                # item['stats_vote'] = div.xpath('.//span[@class="stats_vote"]/i/text()')
                # item['stats_vote'] = item['stats_vote'][0] if len(item['stats_vote']) > 0 else None
                if item['content_img'] is None:
                    content_list.append(item)
            self.content_quene.put(content_list)
            self.html_quene.task_done()

    def save_content_list(self):
        while True:
            content_list = self.content_quene.get()
            with open('qiushibaike.txt', 'a', encoding='utf-8') as f:
                for item in content_list:
                    total_word = ''
                    for words in item['content']:
                        total_word += words
                    f.write(str(self.nums) + '. ' + total_word + '\n')
                    self.nums += 1
            self.content_quene.task_done()

    def run(self):
        thread_list = []
        # 获取url的线程
        t_url = threading.Thread(target=self.get_url_list)
        thread_list.append(t_url)
        # 多个线程去发送请求
        for i in range(10):
            t_parse = threading.Thread(target=self.parse_url)
            thread_list.append(t_parse)
        # 多个线程去提取数据
        for i in range(5):
            t_html = threading.Thread(target=self.get_content_list)
            thread_list.append(t_html)
        # 保存
        t_save = threading.Thread(target=self.save_content_list)
        thread_list.append(t_save)
        for t in thread_list:
            t.setDaemon(True)  # 把子线程设置为守护线程，主线程结束，子线程随之结束
            t.start()

        for q in [self.url_quene, self.html_quene, self.content_quene]:
            q.join()  # 让主线程等待阻塞，等待队列的任务都全部完成

        print('主线程结束')


if __name__ == '__main__':
    qiubai = QiubaiSpider()
    qiubai.run()
